import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Drawer, FormInstance, Popconfirm, Image} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormRadio,
  ProFormUploadButton,
  ProFormTreeSelect, ProFormItem,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {removeData, dataList, dataInit, addData, updateData, loadData} from './service';
import type {ManageRuleBody, ManageRuleListItem, ManageRuleListPagination} from './data';
import {UploadFile} from 'antd/lib/upload/interface';
import {loadOrgList} from '@/pages/Enterprise/Org/service';
import CheckModule from '@/components/CheckModule';
import {IDomEditor, IEditorConfig, IToolbarConfig} from "@wangeditor/editor";
import {upload} from "@/services/ant-design-pro/api";
import {Editor, Toolbar} from "@wangeditor/editor-for-react";

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: ManageRuleBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateData({...fields}) : await addData({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: ManageRuleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.ruleId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const requestOrg = async () => {
  return loadOrgList({status: '0'}).then(({data}) => {
    return data;
  });
};
const ManageRulePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<ManageRuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<ManageRuleListItem[]>([]);

  const columns: ProColumns<ManageRuleListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '文号',
      dataIndex: 'symbol',
      search: false,
    },
    {
      title: '签发人',
      dataIndex: 'signer',
      search: false,
    },
    {
      title: 'APP是否可见',
      dataIndex: 'status',
      search: false,
      valueEnum: {
        0: {
          text: '是',
          status: 'Success',
        },
        1: {
          text: '否',
          status: 'Error',
        },
      },
    },
    {
      title: '附件',
      dataIndex: 'filePath',
      valueType: 'filePath',
      render: (_, record) => (
        <a href={record.filePath} target={"_blank"}>
          查看
        </a>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      defaultSortOrder: 'descend',
    },
    {
      title: '归属部门',
      dataIndex: 'orgId',
      valueType: 'treeSelect',
      request: requestOrg,
      fieldProps: {
        dropdownMatchSelectWidth: false,
        placeholder: '请选择部门',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
        treeLine: true,
        treeDefaultExpandAll: true,
        fieldNames: {label: 'label', value: 'id', children: 'children'},
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            console.log(record);
            setCurrentRow(record);
            setEditMode(true);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          okButtonProps={{danger: true}}
          title={`确认删除管理制度：${record.name}?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>,
      ],
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    multiple: false,
    // @ts-ignore
    onChange({file}) {
      if (file.status === 'done' && file.response.code !== 200) {
        file.status = 'error';
      }
    },
    onPreview: async (file: UploadFile) => {
      window.open(file?.response?.data?.url || file.url, '_blank');
      // setPreviewData({
      //   image: file?.response?.data?.url || file.url,
      //   visible: true,
      //   title: '查看图片',
      // });
    },
    name: 'file',
    // listType: 'picture-card',
    max: 1,
  };
  const submitCheckFile = (
    values: ManageRuleBody,
    fileName: string,
    dataName: string,
    msg: string,
  ) => {
    let file = values[fileName][0];
    if (file.status !== 'done' || (file?.response && file?.response?.code !== 200)) {
      throw new Error(msg);
    }
    values[dataName] = file?.response?.data?.url || file.url;
  };

  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // 编辑器内容
  const [html, setHtml] = useState("");
  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        // 自定义上传
        customUpload: async function (file: File, insertFn: any) {
          // TS 语法
          console.log(file);
          upload(file).then((value) => {
            console.log(value);
            // @ts-ignore
            insertFn(value.data.url, value.data.alt, value.data.href);
          });

          // async customUpload(file, insertFn) {                   // JS 语法
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          // 最后插入图片
        },
        // withCredentials: true,
        // server: 'http://localhost:8080/enterprise/editor/upload',
        // fieldName: 'file',
        // header: {
        //   Authorization: `Bearer ${localStorage.getItem('token')}`
        // }
      },
    },
  };
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  const isDev = process.env.NODE_ENV === 'development';

  return (
    <CheckModule code={'SC'}>
      <PageContainer waterMarkProps={{content: ''}}>
        <ProTable<ManageRuleListItem, ManageRuleListPagination>
          headerTitle="管理制度列表"
          actionRef={actionRef}
          rowKey="ruleId"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="distribute"
              onClick={async () => {
                await dataInit();
                message.success('操作成功');
              }}
            >
              初始化
            </Button>,
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setEditMode(false);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>,
          ]}
          request={dataList}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择{' '}
                <a
                  style={{
                    fontWeight: 600,
                  }}
                >
                  {selectedRowsState.length}
                </a>{' '}
                个管理制度
              </div>
            }
          >
            <Popconfirm
              key="delete"
              title={`确认删除选中的${selectedRowsState.length}个管理制度?`}
              okButtonProps={{danger: true}}
              onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <Button danger>批量删除</Button>
            </Popconfirm>
            {/*<Button type="primary">批量审批</Button>*/}
          </FooterToolbar>
        )}
        <ModalForm<ManageRuleBody>
          title={currentRow?.ruleId || 0 > 0 ? '编辑管理制度' : '新建管理制度'}
          formRef={formRef}
          modalProps={{destroyOnClose: true, maskClosable: false}}
          visible={createModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          onFinish={async (value) => {
            console.log(value);
            try {
              submitCheckFile(value, 'filePathFile', 'filePath', '制度附件未上传');
            } catch ({message: msg}) {
              // @ts-ignore
              message.error(msg);
              // return false;
            }
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current?.reload();
              }
            }
            // return false;
          }}
          request={(params: ManageRuleBody) => {
            console.log(params);
            if (params.ruleId ?? 0 > 0) {
              return loadData(params).then(({data}) => {
                if (data.filePath) {
                  data.filePathFile = [
                    {
                      url: data.filePath,
                      status: 'done',
                    },
                  ];
                }

                return data;
              });
            } else {
              return new Promise<ManageRuleBody>((resolve) => {
                resolve({
                  ruleId: undefined,
                  status: 0,
                  createTime: '',
                });
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="ruleId"/>

          <ProFormText required label={'名称'} name="name"/>
          <ProFormText required label={'文号'} name="symbol"/>
          <ProFormText required label={'签发人'} name="signer"/>
          <ProFormItem required label={'内容'} name="content" rules={[
            {
              required: true,
              message: '内容为必填项',
            },
          ]}>
            <div style={{border: '1px solid #ccc', zIndex: 100}}>
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="simple"
                style={{borderBottom: '1px solid #ccc'}}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => {
                  if (!editor.isEmpty()) {
                    let html1 = editor.getHtml();
                    setHtml(html1);
                    if (html1 == '') {
                    }
                    formRef.current?.setFieldsValue({content: html1});
                  }

                }}
                mode="default"
                style={{height: '200px', overflowY: 'hidden'}}
              />
            </div>
            {isDev ? (<div style={{marginTop: '15px'}}>{html}</div>) : (<></>)}
          </ProFormItem>
          <ProFormUploadButton
            name="filePathFile"
            label="制度附件"
            required
            max={1}
            // @ts-ignore
            fieldProps={{...uploadProps}}
            action="/v2/enterprise/upload/manage-rule"
          />
          <ProFormRadio.Group
            name="status"
            label="APP是否可见"
            options={[
              {
                label: '是',
                value: 0,
              },
              {
                label: '否',
                value: 1,
              },
            ]}
          />

          <ProFormTreeSelect
            width="md"
            request={requestOrg}
            fieldProps={{
              treeLine: true,
              treeDefaultExpandAll: true,
              fieldNames: {label: 'label', value: 'id', children: 'children'},
              onChange: (value) => {
                console.log(value);
              },
            }}
            name="orgId"
            label="归属部门"
          />
        </ModalForm>

        <Image
          width={200}
          style={{display: 'none'}}
          src={previewData.image}
          preview={{
            visible: previewData.visible,
            src: previewData.image,
            onVisibleChange: (value) => {
              setPreviewData({image: previewData.image, title: '', visible: value});
            },
          }}
        />
        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.ruleId && (
            <ProDescriptions<ManageRuleBody>
              column={1}
              bordered={true}
              title={'管理制度详情'}
              request={loadData}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<ManageRuleBody>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default ManageRulePage;
